<template>
  <div
    class="page-Body"
    v-if="!$route.params.communityId || $route.name === 'activityment'"
  >
    <h2 class="page-title">活动管理</h2>
    <!-- 表单 -->
    <el-form :inline="true" :model="formInline">
      <el-form-item label="活动名称">
        <el-input
          v-model="formInline.title"
          placeholder="请输入活动名称"
          clearable
          style="width: 145px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="活动分类">
        <el-input
          v-model="formInline.typeName"
          placeholder="请输入活动分类"
          clearable
          style="width: 145px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="活动状态">
        <el-select
          v-model="formInline.activityStatus"
          placeholder="请选择活动状态"
          clearable
          style="width: 150px"
          v-noSpace
        >
          <el-option
            v-for="item in activityStatusList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <TimeFormatter
          @TimeChild="TimeHandle"
          ref="childComponentRef"
          style="width: 350px"
        ></TimeFormatter>
      </el-form-item>
      <el-form-item label="发起人">
        <el-input
          v-model="formInline.initiatorUid"
          placeholder="请输入发起人"
          clearable
          style="width: 145px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="Search">搜索</el-button>
        <el-button @click="Reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      fit
      empty-text="暂无数据"
      show-header
      v-loading="loading"
      size="default"
      element-loading-text="Loading..."
      :header-cell-style="{ background: '#e7e1fb' }"
      style="width: 100%"
      max-height="600px"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="title" label="活动名称" />
      <el-table-column prop="typeName" label="活动分类" />
      <el-table-column prop="tags" label="活动标签" v-slot="scope">
        <el-tag
          v-for="(item, index) in scope.row.tags || []"
          :key="index"
          style="margin-right: 5px"
        >
          {{ item }}
        </el-tag>
      </el-table-column>
      <el-table-column prop="releaseTime" label="发起时间" />
      <el-table-column prop="initiatorUid" label="活动创建人" />
      <el-table-column prop="activityStatusStr" label="活动状态">
        <template #default="scope">
          <span :style="{ color: getStatusColor(scope.row.activityStatusStr) }">
            {{ scope.row.activityStatusStr }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="reviewStatusStr" label="审核状态">
        <template #default="scope">
          <span
            :style="{ color: ProcessStatusColor(scope.row.reviewStatusStr) }"
          >
            {{ scope.row.reviewStatusStr }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="reviewStatus" label="下架">
        <template #default="scope">
          {{ scope.row.reviewStatus === 3 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        v-slot="scope"
        width="400"
      >
        <el-button
          link
          type="primary"
          @click="ActivityDetails(scope.row.activityId)"
        >
          查看详情
        </el-button>
        <el-button
          link
          type="primary"
          @click="ActivityMember(scope.row.activityId)"
        >
          查看成员
        </el-button>
        <el-button
          link
          type="primary"
          @click="ActivityData(scope.row.activityId)"
        >
          活动数据
        </el-button>
        <el-button
          link
          type="primary"
          @click="ActivityEvaluate(scope.row.activityId)"
        >
          活动评价
        </el-button>
        <el-button
          link
          type="danger"
          @click="ActivityRemoval(scope.row.activityId)"
        >
          活动下架
        </el-button>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 80, 100]"
        background
        layout="total,sizes, prev, pager, next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 活动下架对话框 -->
    <ActivityRemoval_Dialog
      @confirm="RemovalConfirm"
      @cancel="RemovalClose"
      :activityId="activityId"
      :dialogRemoval="dialogRemoval"
    />
    <ActivityDetails_Dialog
      @cancel="DetailsClose"
      :dialogDetails="dialogDetails"
      :activityId="activityId"
    />
  </div>
  <div v-else>
    <router-view :key="$route.fullPath"></router-view>
  </div>
</template>

<script setup name="ActivityManagementPage">
import { getActivityList } from '@/api/Activity/ActivityMent.js';
import ActivityRemoval_Dialog from '@/components/Activity/ActivityMent/activityRemoval_Dialog.vue';
import ActivityDetails_Dialog from '@/components/Activity/ActivityMent/ActivityDetail_Dialog.vue';
import TimeFormatter from '@/components/permission/TimeFormatter.vue';
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const activityStatusList = ref([
  {
    id: 0,
    label: '未发布',
    value: 'UNRELEASED',
  },
  {
    id: 1,
    label: '已发布',
    value: 'RELEASED',
  },
  {
    id: 2,
    label: '进行中',
    value: 'UNDERWAY',
  },
  {
    id: 3,
    label: '已结束',
    value: 'FINISHED',
  },
  {
    id: 4,
    label: '已取消',
    value: 'CANCEL',
  },
]);
// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
// 表单-时间选择器
const childComponentRef = ref(null);
const TimeArray = ref([]);
// 表单数据
const formInline = ref({
  title: '',
  typeName: '',
  activityStatus: '',
  initiatorUid: '',
});
const activityId = ref('');

// 对话框
const dialogRemoval = ref(false);
const dialogDetails = ref(false);
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);

// 获取列表
const activityList = async () => {
  loading.value = true;
  const params = {
    current: currentPage.value,
    size: pageSize.value,
    startDate: TimeArray.value[0],
    endDate: TimeArray.value[1],
    query: {
      ...formInline.value,
    },
  };

  // 只有在从社群管理进入且有communityId参数时才添加communityId
  if (route.params.communityId && route.params.communityId !== ':communityId') {
    params.query.communityId = route.params.communityId;
  }

  const res = await getActivityList(params);
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 监听路由参数变化
watch(
  () => route.params.communityId,
  (newId) => {
    if (newId && newId !== ':communityId') {
      activityList();
    }
  },
  { immediate: true }
);

// 分页逻辑
const handleSizeChange = async (val) => {
  pageSize.value = val;
  activityList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  activityList();
};

// 搜索校验
const hasSearchConditions = () => {
  const { title, typeName, activityStatus, initiatorUid } = formInline.value;
  return (
    title ||
    typeName ||
    (activityStatus !== undefined && activityStatus !== '') ||
    initiatorUid ||
    (TimeArray.value && TimeArray.value.length > 0)
  );
};
// 搜索
const Search = async () => {
  if (!hasSearchConditions()) {
    // eslint-disable-next-line no-undef
    ElMessage({
      message: '请至少输入一个搜索条件或选择时间范围',
      type: 'warning',
    });
    return;
  }
  activityList();
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (
    formInline.value.title === '' &&
    formInline.value.typeName === '' &&
    formInline.value.activityStatus === '' &&
    formInline.value.initiatorUid === '' &&
    (!TimeArray.value || TimeArray.value.length === 0)
  ) {
    return;
  }
  formInline.value = {};
  TimeArray.value = [];
  if (childComponentRef.value) {
    childComponentRef.value.clear();
  }
  activityList();
};
// 获取活动状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case '已发布':
      return '#00B42A';
    case '已开始':
      return '#00B42A';
    case '审核中':
      return '#FFAE35 ';
    case '已结束':
      return '#FF4E4E';
    default:
      return '#303133';
  }
};
// 获取活动状态颜色
const ProcessStatusColor = (status) => {
  switch (status) {
    case '审核通过':
      return '#00B42A';
    case '审核中':
      return '#FFAE35 ';
    case '审核未通过':
      return '#FF4E4E';
    default:
      return '#303133';
  }
};
//获取时间
const TimeHandle = (data) => {
  TimeArray.value = data;
};
// 下架对话框
const ActivityRemoval = (Id) => {
  dialogRemoval.value = true;
  activityId.value = Id;
};
const RemovalConfirm = () => {
  dialogRemoval.value = false;
  activityList();
};
const RemovalClose = () => {
  dialogRemoval.value = false;
};
// 查看活动详情
const ActivityDetails = (id) => {
  dialogDetails.value = true;
  activityId.value = id;
};
const DetailsClose = () => {
  dialogDetails.value = false;
};
// 优化路由跳转方法
const handleRouteChange = (name, id) => {
  router
    .push({
      name,
      params: { id },
    })
    .catch((err) => {
      console.error('路由跳转失败:', err);
    });
};
// 查看活动成员
const ActivityMember = (id) => {
  handleRouteChange('activitymentMember', id);
};
// 查看活动数据
const ActivityData = (id) => {
  handleRouteChange('activitymentData', id);
};
// 查看活动评价
const ActivityEvaluate = (id) => {
  handleRouteChange('activitymentEvaluate', id);
};
onMounted(() => {
  activityList();
});
</script>

<style lang="scss" scoped></style>
